package com.qf.blog.controller;

import com.qf.blog.constatns.LoginConstatns;
import com.qf.blog.entity.User;
import com.qf.blog.service.IUserService;
import com.qf.blog.service.impl.UploadFileService;
import com.qf.blog.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
@RestController
public class FileUploadController {
    @Autowired
    private UploadFileService uploadFileService;

    @Autowired
    private IUserService userService;

    @RequestMapping("/uploadFile")
    @ResponseBody
    public Result uploadFile(MultipartFile file, HttpSession session) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();

        // 1.把头像上传到七牛云服务器上面
        String fileUrl = uploadFileService.uploadFile(inputStream, size, originalFilename);
        System.out.println("七牛云返回的地址："+fileUrl);

        // 2、修改用户的头像地址
        User user = (User) session.getAttribute(LoginConstatns.LOGIN_USER_KEY);
        userService.updateUserHeaderUrl(fileUrl,user.getId());
        return Result.success();
    }
}
